<template>
  <table border="1" cellspacing="0">
    <tr>
      <th>编号</th>
      <th>名称</th>
      <th>单价</th>
      <th>数量</th>
      <th>小计</th>
    </tr>
    <tr v-for="(value, index) in cart.lists" :key="value.pname">
      <td>{{ index + 1 }}</td>
      <td>{{ value.pname }}</td>
      <td>{{ value.price }}</td>
      <td>
        <input type="button" value="+" @click="value.count++" />
        {{ value.count }}
        <input
          type="button"
          value="-"
          @click="value.count > 0 ? value.count-- : 0"
        />
      </td>
      <td>{{ value.price * value.count }}</td>
    </tr>
    <!-- 总计 -->
    <tr>
      <td colspan="4" align="center">总计</td>
      <td>{{ totalPrice }}</td>
    </tr>
  </table>
</template>

<script>
import { reactive, computed } from "vue";

export default {
  setup() {
    const cart = reactive({
      lists: [
        { pname: "apple", price: 3, count: 2, sub: 6 },
        { pname: "pear", price: 4, count: 3, sub: 12 },
        { pname: "banana", price: 5, count: 4, sub: 20 },
      ],
    });

    const totalPrice = computed(() => {
      return cart.lists.reduce((sum, list) => sum + list.price * list.count, 0);
    });

    return { cart, totalPrice };
  },
};
</script>
